﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Antioch.Base.PlayerStates
{
    internal class Push : IState
    {
        public void Enter(StateMachine Machine)
        {
            Machine.DrawComponent.Play("Push", true);
            Machine.PhysicsComponent.PhysicsBody.GetFixtureList().SetFriction(0.8f);
            
        }

        public void Leave(StateMachine Machine)
        {
            
        }

        public void Update(StateMachine Machine)
        {
            if (Machine.Input.Hurt)
            {
                Machine.Transition(typeof(Flinch));
                return;
            }
            else if (!Machine.PhysicsComponent.IsOnGround)
            {
                Machine.Transition(typeof(Fall));
                return;
            }
            else if (!Machine.Input.UsePressed)
            {
                Machine.Transition(typeof(Stand));
                return;
            }


            var Body = Machine.Memory.PushPullPoint.GetPhysicsBody();
            if (Body != null)
            {


                if ((Machine.PlayerEntity.Facing == Jemgine.Data.Facings.Right && Machine.Input.NavigationStick.X > 0) ||
                    (Machine.PlayerEntity.Facing == Jemgine.Data.Facings.Left && Machine.Input.NavigationStick.X < 0))
                {
                    Vector2 Right = Jemgine.Math.Vector.Perpendicular(Machine.PhysicsComponent.GroundNormal);
                    Right.Normalize();
                    Body.ApplyLinearImpulse(Right * 64 * Machine.Input.NavigationStick.X, Body.Position);

                    Machine.PhysicsComponent.PhysicsBody.ApplyLinearImpulse(
                        Right * Machine.Settings.RunForce * Machine.Input.NavigationStick.X,
                        Machine.PhysicsComponent.PhysicsBody.Position);

                }
                else
                    Machine.Transition(typeof(Grab));
            }

            Vector2 GrabSpot = new Vector2(0, 0);
            GrabSpot = Machine.PlayerEntity.TransformToWorldSpace(GrabSpot);

            var GrabBox = new Jemgine.Math.OBB();
            GrabBox.Center = GrabSpot;
            GrabBox.Extents = Machine.PhysicsComponent.Dimensions / 2;
            GrabBox.Angle = Machine.PhysicsComponent.PhysicsBody.GetAngle();

            if (!Jemgine.Math.OBB.Intersect(GrabBox, Machine.Memory.PushPullPoint.GetWorldOBB()))
                Machine.Transition(typeof(Stand));
            else if (!Machine.Memory.PushPullPoint.CanGrab(Machine.PlayerEntity))
                Machine.Transition(typeof(Stand));
        }
    }
}
